package com.zhihu.utils;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.MultimediaInfo;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import ws.schild.jave.MultimediaObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class GetVideoInfo {

    /**
     * 描述：截取视频中图片作为封面
     * @author zwh 2021.5.18 10:25
     */
    public String[] getVideoImg(String videoPath){

        String pngPath = "";
        FFmpegFrameGrabber ff=null;

        try {
            ff = FFmpegFrameGrabber.createDefault(new File(videoPath));
            ff.start();
            int ffLength = ff.getLengthInFrames();
            Frame f;
            int i = 1;
            String weizhi="";
            String [] imgPath = new String[8];
            while (i < ffLength) {
                f = ff.grabFrame();
                //截取第20帧
                if ((i < 10) && (f.image != null)) {
                    //生成图片的相对路径 例如：pic/uuid.png
                    pngPath = UUID.randomUUID().toString().replace("-", "")+".png";
                    //执行截图并放入指定位置
                    //System.out.println("存储图片 ： " + (dir + pngPath));
                    weizhi = doExecuteFrame(f, "C:\\Users\\MI\\Desktop\\" + pngPath);
                    imgPath[i-1]="C:\\Users\\MI\\Desktop\\" + pngPath;
                    break;
                }
                i++;
            }
            ff.stop();
            return imgPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //返回图片生成的路径
    private static String doExecuteFrame(Frame f, String targerFilePath) {
        String imagemat = "png";
        if (null == f || null == f.image) {
            return null;
        }
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bi = converter.getBufferedImage(f);
        File output = new File(targerFilePath);
        System.err.println("output="+output);
        try {
            ImageIO.write(bi, imagemat, output);
            return output.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取视频的时长
    public Date getVideoTime(MultipartFile contentFile) throws InputFormatException, EncoderException {
        // 将MultipartFile转换为Encoder所需的File
        CommonsMultipartFile cf = (CommonsMultipartFile) contentFile;
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File source = fi.getStoreLocation();
        // 获取视频时长
        Encoder encoder = new Encoder();
        MultimediaInfo m = encoder.getInfo(source);
        long ls = m.getDuration() / 1000;
        int hour = (int) (ls / 3600);
        int minute = (int) (ls % 3600) / 60;
        int second = (int) (ls - hour * 3600 - minute * 60);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

        String date = ""+((hour/10==0 || hour==0)?("0"+hour%10):hour) +":"+ ((minute/10==0 || minute==0)?("0"+minute%10):minute) +":"+ ((second/10==0 || second==0)?("0"+second%10):second);
        try {
            Date parse = simpleDateFormat.parse(date);
            return parse;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取视频时长
     * @param FileUrl
     * @return
     */

    /*
    public static String ReadVideoTime(String FileUrl) {
        File source=new File(FileUrl);
        String length = "";
        try {
            MultimediaObject instance = new MultimediaObject(source);
            MultimediaInfo result = instance.getInfo();
            long ls = result.getDuration() / 1000;
            Integer hour = (int) (ls / 3600);
            Integer minute = (int) (ls % 3600) / 60;
            Integer second = (int) (ls - hour * 3600 - minute * 60);
            String hr=hour.toString();
            String mi=minute.toString();
            String se=second.toString();
            if(hr.length()<2){
                hr="0"+hr;
            }
            if(mi.length()<2){
                mi="0"+mi;
            }
            if(se.length()<2){
                se="0"+se;
            }
            length = hr + ":" + mi + ":" + se;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length;
    }*/


    /**
     * 获取视频大小
     * @param multipartFile
     * @return
     */
    public String ReadVideoSize(MultipartFile multipartFile) {
        FileChannel fc = null;
        String size = "";
        try {
            CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
            DiskFileItem fi = (DiskFileItem) cf.getFileItem();
            File source = fi.getStoreLocation();
            FileInputStream fis = new FileInputStream(source);
            fc = fis.getChannel();
            BigDecimal fileSize = new BigDecimal(fc.size());
            size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fc) {
                try {
                    fc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return size;
    }
}
